<template>
	<view>
		<template v-if="goodsList.length">
			<!-- 商品列表 -->
			<view class="j-i-goods-list">
				<view class="j-i-goods-item" @click="toGoodsDetails(item)" v-for="(item, index) in goodsList" :key="index">
					<goods :goods="item"></goods>
				</view>
			</view>
			<u-loadmore :status="loadStatus" bg-color="#f3f3f3" :margin-bottom="20"/>
		</template>
		<template v-else>
			<view class="j-a-empty"><u-empty></u-empty></view>
		</template>
	</view>
</template>

<script>
	export default{
		data() {
			return {
				params:{
					page: 0,
					rows: 10,
					goodsTypeId:''
				},
				goodsList:[],
				loadStatus: 'loadmore'
			}
		},
		onLoad(e) {
			this.params.goodsTypeId = e.goodsTypeId;
			uni.setNavigationBarTitle({
				title: e.goodsTypeName
			})
			this.pullUp();
		},
		onPullDownRefresh() {
			this.dropDown()
		},
		onReachBottom() {
			this.pullUp();
		},
		methods:{
			// 下拉刷新
			dropDown() {
				// 修改当前view的数据
				this.params.page = 1;
				// 加载下拉刷新的数据
				this.postFindGoodsListByType('down');
			},
			// 上拉加载
			pullUp() {
				// 增加页数
				this.params.page++;
				// 请求获取数据
				this.postFindGoodsListByType('up');
			},
			// 首页-根据分类ID查询商品列表
			postFindGoodsListByType(type){
				this.$u.api
					.postFindGoodsListByType(this.params)
					.then(res => {
						console.log(res, '[商品列表页-根据分类ID查询商品列表]');
						uni.stopPullDownRefresh();
						
						if(res.data.rows.length){
							res.data.rows.forEach(v => {
								v.imageFirst = JSON.parse(v.goodsImages)[0];
							});
						}
						
						// 如果是上拉加载
						if (type == 'up') {
							// 判断分页
							if (this.params.page <= res.data.totalPage) {
								
								this.goodsList.push(...res.data.rows);
								this.loadStatus = 'loading';
						
								// 如果数量小于页容量，显示没有更多数据
								if (res.data.rows.length < this.params.rows) {
									this.loadStatus = 'nomore';
								}
							} else {
								this.params.page = res.data.totalPage;
								this.loadStatus = 'nomore';
							}
						}
						
						// 如果是下拉刷新
						if (type == 'down') {
							// 将数据
							this.goodsList.push(...res.data.rows);
							this.goodsList.splice(0, this.goodsList.length == 0 ? 0 : this.goodsList.length - res.data.rows.length);
						}
						
					})
					.catch(err => {
						console.log(err);
					});
			},
			// 跳转商品详情页面
			toGoodsDetails(item) {
				uni.navigateTo({
					url: './goods-details?goodsMallId=' + item.goodsMallId
				});
			}
		}
	}
</script>

<style>
	page{
		background-color: #F3F3F3;
	}
</style>
<style scoped lang="scss">
	.j-a-empty {
		margin-top: 60rpx;
	}
	.j-i-goods-list {
		display: flex;
		flex-wrap: wrap;
		padding: 0 25rpx;
		justify-content: space-between;
	
		.j-i-goods-item {
			margin-bottom: 25rpx;
		}
	}
</style>
